# coding=utf-8
# Date: 11-12-8
# Time: 下午10:28
import collections
import json

from django.http import HttpResponse

from util.basemodel import JSONBaseMixin

__author__ = u'王健'


from django.core.cache import cache


class JSONHttpResponse(HttpResponse):
    """
    继承HttpResponse类
    by:王健 at:2015-08-24
    """

    def __init__(self, json=None, *args, **kwargs):
        super(JSONHttpResponse, self).__init__(*args, **kwargs)
        self.json = json


def getErrorFormResult(form):
    msg = form.json_error()
    return getResult(False, msg, None)


def getCacheResult(cache_name):
    """
    返回缓存的数据
    by:王健 at:2015-1-3
    优化缓存结果的非空判断
    by:王健 at:2015-05-21
    :param cache_name:
    :return:
    """
    cache_result = cache.get(cache_name)
    if cache_result is not None:
        return HttpResponse(cache_result)
    else:
        return


def is_success_mongodb_result(result):
    """
    根据mongo的返回信息，判断本次是否成功
    by:王健 at:2015-1-3
    :param result:
    :return:
    """
    if hasattr(result, 'err') and result['err'] is not None:
        return False
    else:
        return True


def getResult(success, message, result=None, status_code=0, dialog=0, jifen=None, p_index=None, p_count=None,
              total_count=None):
    """
    0 正常返回 code
    """
    message = message or ""
    map = {'msg': message, 'msgCode': status_code}
    if result:
        map['data'] = MyEncoder.default(result)
    if not success and status_code == 0:
        map['msgCode'] = -1
    jsonstr = json.dumps(map)
    return JSONHttpResponse(content=jsonstr, json=map, content_type=u'application/json')

def getResult_status(success, message, result=None, status_code=0, dialog=0, jifen=None, p_index=None, p_count=None,
              total_count=None):
    "创建项目返回字段无法覆盖问题"
    #复制getResult 单独返回字段为0;
    message = message or ""
    map = {'success': success, 'message': message, 'status_code': status_code, 'dialog': dialog}
    if result:
        map['result'] = MyEncoder.default(result)
    if not success and status_code == 0:
        map['status_code'] = 0
    # if jifen and jifen[0]:
    #     map['jifen'] = jifen[1]
    #     map['jifen_msg'] = jifen[2]
    if p_index != None and p_count != None:
        map['p_index'] = p_index
        map['p_count'] = p_count
    if total_count:
        map['total_count'] = total_count
    jsonstr = json.dumps(map)
    return JSONHttpResponse(content=jsonstr, json=map, content_type=u'application/json')


def getTestResult(success, message, result=None, status_code=0, dialog=0, jifen=None):
    '''
    单元测试 使用
    by:王健 at:2015-1-3
    优化返回结构的 status_code
    by:王健 at:2015-1-10
    增加积分
    by:王健 at:2015-2-5
    '''
    map = {'success': success, 'message': message, 'status_code': status_code, 'dialog': dialog}
    if result:
        map['result'] = MyEncoder.default(result)
    if not success and status_code == 0:
        map['status_code'] = 4
    if jifen and jifen[0]:
        map['jifen'] = jifen[1]
        map['jifen_msg'] = jifen[2]
    return map


class MyEncoder():
    """
    继承自simplejson的编码基类，用于处理复杂类型的编码
    by:王健 at:2015-1-3
    对list类型的不做处理，view中还是主要以返回QuerySet为主
    by:王健 at:2015-1-7
    不再继承一个class了，直接用json模块
    by:王健 at:2015-1-13
    """

    @staticmethod
    def default(obj):
        """
        优化Model 序列化 功能
        by:王健 at:2015-1-29
        优化 序列化算法
        by:王健 at:2015-3-9
        修改序列化算法
        by: 范俊伟 at:2015-08-24
        :param obj:
        :return:
        """
        if isinstance(obj, dict):
            return obj
        if isinstance(obj, collections.Iterable):
            l = []
            for o in obj:
                if isinstance(o, JSONBaseMixin):
                    l.append(o.toJSON())
                elif hasattr(o,'toJSON'):
                    l.append(o.toJSON())
                else:
                    l.append(o)
            return l
        if isinstance(obj, JSONBaseMixin):
            return obj.toJSON()

        return None
